package com.gaohe.controller;



import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.BaseContext;
import com.gaohe.common.R;
import com.gaohe.pojo.Admin;
import com.gaohe.service.AdminService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdminService adminService;
      @PostMapping("/login")
      public R login(@RequestBody Admin admin, HttpSession session){
         // System.out.println(admin);
         //1.接收参数
          String username=admin.getUsername();
          String password=admin.getPassword();
          //密码加密：
           password = MD5.create().digestHex(password);
          //2.根据用户名查询用户
          LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
          qw.eq(Admin::getUsername,username);
          Admin admin1 = adminService.getOne(qw);
          //3.没有查到-》用户名不存在
          if(StringUtils.isEmpty(admin1)){
              log.info("用户名不存在");
              return R.error("用户名不存在");
          }
         //4.密码不相同-》密码错误
          if(StringUtils.isEmpty(password)||!admin1.getPassword().equals(password)){
              log.info("密码错误");
              return R.error("密码错误");
          }
          //5.判断是否禁用
          if(admin1.getStatus()==0){
              log.info("用户已停用");
              return R.error("用户已停用");
          }
          //6.存入会话
           //session.setAttribute("user",admin1.getId());
          redisTemplate.opsForValue().set("auth"+admin1.getId(),admin1.getId(),30, TimeUnit.MINUTES);
          //7.登陆成功
          return R.success(admin1);

      }
      //登出
      @GetMapping("/logout")
      public R logout(){
          //从会话中删除标识
          Long currentId = BaseContext.getCurrentId();
          redisTemplate.delete("auth"+currentId);
         return R.success("登出成功");

      }
      //管理员分页查询
    @GetMapping("/page")
      public R page(@RequestParam int page,
                    @RequestParam int pageSize,
                    @RequestParam(required = false) String name)
    {
        //1.接收参数
        log.info("当前页：{}，页条数：{}，条件：{}",page,pageSize,name);
        //2.分页条件
        Page<Admin> adminPage = new Page<>(page,pageSize);
        //查询条件
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Admin::getName,name);
        qw.orderByDesc(Admin::getUpdateTime);//添加排序规则

        //3.分页查询
        adminService.page(adminPage,qw);
        //4.返回值
        return R.success(adminPage);
    }
    //新增管理员
    @PostMapping
    public R save(@RequestBody Admin admin,HttpSession session){
          //1.接收参数
          log.info("新增数据：{}",admin);
          //2.字段处理
        admin.setStatus(1);
//        admin.setCreateTime(LocalDateTime.now());
//        admin.setUpdateTime(LocalDateTime.now());
        //session获取操作者
        Long user = (Long)session.getAttribute("user");
        admin.setUpdateUser(user);
        admin.setCreateUser(user);

        boolean b = adminService.save(admin);
        return b?R.success("新增成功"):R.error("新增失败");
    }
    //根据id修改员工状态
    @PutMapping("/changeStatus")
    public R changeStatus(@RequestBody Admin admin){
         //1.接收参数
        log.info("根据ID修改员工状态：{}",admin);
        //long类型超过16位浏览器会出现失真问题数字传递假值
        //springMVC消息转换器解决long->String
        //维护修改字段
//        admin.setUpdateTime(LocalDateTime.now());
//        Long user =(Long) session.getAttribute("user");
//        admin.setUpdateUser(user);
        //2.修改
        boolean b = adminService.updateById(admin);
        return b?R.success("修改成功"):R.error("修改失败");
    }
    //根据ID查询信息
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){
          return R.success(adminService.getById(id));
    }
    //根据ID修改
    @PutMapping
    public R updateById(@RequestBody Admin admin){
          //修改
        //密码加密
        admin.setPassword(MD5.create().digestHex(admin.getPassword()));
        boolean b = adminService.updateById(admin);
        return b?R.success("修改成功"):R.error("修改失败");
    }

    @GetMapping
    public R page(){
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.select(Admin::getName,Admin::getPhone);
        List<Admin> list = adminService.list(qw);
        return R.success(list);
    }




}
